<template>
    <div class="app-container output">
        <el-row :gutter="24">
            <el-col :span="span">
                <el-card :header="$t('lan1')">
                    <el-form :model="netConfig" ref="netFormRef" label-width="100px" :rules="rules"
                        style="width: 75%;height: 450px;margin:0 auto">

                        <el-form-item label="DHCP" prop="dhcp" v-if="hardware.function?.dhcp">
                            <el-switch v-model="netConfig.dhcp" inline-prompt active-text="ON"
                                inactive-text="OFF"></el-switch>
                        </el-form-item>

                        <el-form-item label="IP" prop="ip">
                            <el-input v-model="netConfig.ip" :placeholder="$t('input_placeholder')"></el-input>
                        </el-form-item>

                        <el-form-item :label="$t('mask')" prop="mask">
                            <el-input v-model="netConfig.mask" :placeholder="$t('input_placeholder')"></el-input>
                        </el-form-item>

                        <el-form-item :label="$t('gateway')" prop="gateway">
                            <el-input v-model="netConfig.gateway" :placeholder="$t('input_placeholder')"></el-input>
                        </el-form-item>

                        <el-form-item label="DNS" prop="dns">
                            <el-input v-model="netConfig.dns" :placeholder="$t('input_placeholder')"></el-input>
                        </el-form-item>

                        <el-form-item :label="$t('mac')">
                            <el-input v-model="mac" :placeholder="$t('input_placeholder')"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" size="large" @click="saveNet">{{ $t('Save') }}</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </el-col>
            <el-col :span="span" v-if="hardware.capability?.eth1">
                <el-card :header="$t('lan2')">
                    <el-form :model="netConfig2" ref="net2FormRef" label-width="100px" :rules="rules"
                        style="width: 75%;height: 450px;margin:0 auto">

                        <el-form-item label="DHCP" prop="dhcp" v-if="hardware.function?.dhcp">
                            <el-switch v-model="netConfig2.dhcp" inline-prompt active-text="ON"
                                inactive-text="OFF"></el-switch>
                        </el-form-item>

                        <el-form-item label="IP" prop="ip">
                            <el-input v-model="netConfig2.ip" :placeholder="$t('input_placeholder')"></el-input>
                        </el-form-item>

                        <el-form-item :label="$t('mask')" prop="mask">
                            <el-input v-model="netConfig2.mask" :placeholder="$t('input_placeholder')"></el-input>
                        </el-form-item>

                        <el-form-item :label="$t('gateway')" prop="gateway">
                            <el-input v-model="netConfig2.gateway" :placeholder="$t('input_placeholder')"></el-input>
                        </el-form-item>

                        <el-form-item label="DNS" prop="dns">
                            <el-input v-model="netConfig2.dns" :placeholder="$t('input_placeholder')"></el-input>
                        </el-form-item>

                        <el-form-item :label="$t('mac')">
                            <el-input v-model="mac2" :placeholder="$t('input_placeholder')"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" size="large" @click="saveNet2">{{ $t('Save') }}</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </el-col>
            <el-col :span="span" v-if="hardware.function?.wifi">
                <el-card :header="$t('wifi')">
                    <el-form :model="wifiConfig" ref="wifiFormRef" label-width="100px" :rules="rules"
                        style="width: 75%;height: 450px;margin:0 auto">
                        <el-form-item label="SSID">
                            <el-input v-model="wifiSsid" :placeholder="$t('input_placeholder')" :disabled="true"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="handleAdd">{{ $t('Add') }} wifi</el-button>
                            <el-button type="primary" @click="handleMange">{{ $t('Manage') }} wifi</el-button>
                        </el-form-item>
                        <el-form-item :label="$t('enable')" prop="enable">
                            <el-switch v-model="wifiConfig.enable" inline-prompt active-text="ON"
                                inactive-text="OFF"></el-switch>
                        </el-form-item>
                        <el-form-item label="DHCP" prop="dhcp">
                            <el-switch v-model="wifiConfig.dhcp" inline-prompt active-text="ON"
                                inactive-text="OFF"></el-switch>
                        </el-form-item>
                        <el-form-item label="IP" prop="ip">
                            <el-input v-model="wifiConfig.ip" :placeholder="$t('input_placeholder')"></el-input>
                        </el-form-item>

                        <el-form-item :label="$t('mask')" prop="mask">
                            <el-input v-model="wifiConfig.mask" :placeholder="$t('input_placeholder')"></el-input>
                        </el-form-item>

                        <el-form-item :label="$t('gateway')" prop="gateway">
                            <el-input v-model="wifiConfig.gateway" :placeholder="$t('input_placeholder')"></el-input>
                        </el-form-item>

                        <el-form-item label="DNS" prop="dns">
                            <el-input v-model="wifiConfig.dns" :placeholder="$t('input_placeholder')"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" size="large" @click="saveWifi">{{ $t('Save') }}</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </el-col>
        </el-row>

        <el-dialog :title="`${$t('Add')} wifi`" v-model="addDialogVisible" width="600px">
            <el-form v-model="addWifiForm" label-width="100px" style="width: 75%;margin:0 auto">
                <el-form-item label="SSID">
                    <div style="display: flex;justify-content: space-between;align-items: center;width: 100%;">

                        <el-select v-model="addWifiForm.ssid" :placeholder="$t('select_placeholder')" style="width: 100%;margin-right: 15px;">
                            <el-option v-for="item in addWifiOptions" :key="item.value" :label="item.label"
                                :value="item.value" :disabled="item.disabled"></el-option>
                        </el-select>

                        <el-button type="primary" @click="scanWifi">{{ $t('Refresh') }}</el-button>
                    </div>


                </el-form-item>
                <el-form-item :label="$t('Password')">
                    <el-input v-model="addWifiForm.passwd" type="password" show-password
                        :placeholder="$t('input_placeholder')"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="connectWifi">{{ $t('Connect') }}</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <el-dialog :title="`${$t('Manage')} wifi`" v-model="manageDialogVisible" width="600px">
            <div class="wifi-item" v-for="wifi in wifiList">
                <span><b>{{ wifi.ssid }}</b>{{ wifi.flags == "[CURRENT]" ? ` [${$t('Current')}] ` : '' }}{{ wifi.flags ==
                    "[DISABLED]" ? ` [${$t('Disable')}] ` : '' }}</span>
                <span>
                    <el-button type="primary" @click="setWifi('enable_network', String(wifi.id))">{{ $t('Enable')
                    }}</el-button>
                    <el-button type="primary" @click="setWifi('disable_network', String(wifi.id))">{{ $t('Disable')
                    }}</el-button>
                    <el-button type="primary" @click="setWifi('remove_network', String(wifi.id))">{{ $t('Delete')
                    }}</el-button>
                </span>
            </div>
        </el-dialog>
    </div>
</template>

<script setup name="output">
import modal from "@/plugins/modal.js"
import { RPC, RPC2 } from "@/api/rpc"
import FUNC from "@/api/func"
import getJson from "@/api/getJson"
import i18n from '@/lang'
import { nextTick } from 'vue'

let span = ref(8)

let hardware = reactive({})
// let config = reactive([])
handleInit()
function handleInit() {
    // config.length = 0
    let p1 = getJson('/config/hardware.json')
    // let p2 = getJson('/config/config.json')

    Promise.all([p1]).then(res => {

        let [r1] = res

        hardware = Object.assign(hardware, r1.data)
        let arr = [hardware.capability?.eth1, hardware.function?.wifi].filter(Boolean)

        span.value = arr.length == 0 ? 24 : arr.length == 1 ? 12 : 8

        // config.push(...r2.data)

    })
}
// 网口1
let netConfig = reactive({})
getJson("/config/net.json").then(res => {
    Object.assign(netConfig, res.data)
})
let mac = ref('')
getJson("/config/mac").then(res => {
    mac.value = foramtMac(res.data)
})

// 网口2
let netConfig2 = reactive({})
getJson("/config/net2.json").then(res => {
    Object.assign(netConfig2, res.data)
})
let mac2 = ref('')
getJson("/config/mac2").then(res => {
    mac2.value = foramtMac(res.data)
})


// wifi
let wifiConfig = reactive({})
getJson("/config/wifi.json").then(res => {
    Object.assign(wifiConfig, res.data)
})
let wifiSsid = ref('')
getJson("/config/ssid.json").then(res => {
    wifiSsid.value = res.data.ssid
})

function foramtMac(str) {
    if (!str) return ''
    str = str.replace(/[\r\n]/g, "").toUpperCase()
    let result = ''
    for (var i = 0; i < str.length; i += 2) {
        result += str.substr(i, 2);
        if (i + 2 < str.length)
            result += ":";
    }
    return result;
}

let addDialogVisible = ref(false)
let addWifiForm = reactive({})
let addWifiOptions = ref([])

function handleAdd() {
    addDialogVisible.value = true
    scanWifi()
}
function scanWifi() {
    RPC2("wifi.scanWifi", null).then(res => {
        if (res.data.error) {
            showError(res.data.error)
            return
        }
        let list = res.data.result
        if (list.length) {
            addWifiOptions.length = 0
            list.forEach(d => {
                var text = d.ssid;
                if (d.flags == "open") {
                    text += '[open]';
                }
                addWifiOptions.value.push({ value: d.ssid, label: text })
            })
            addWifiForm.ssid = addWifiOptions.value[0].value
        }
    })
}
function connectWifi() {
    RPC2("wifi.addWifi", [addWifiForm.ssid, addWifiForm.passwd]).then(res => {
        if (res.data.error) {
            showError(res.data.error)
            return
        }

        modal.msgSuccess(`${i18n.global.t('Add success')}: ${i18n.global.t('Add success Msg')}`)
    })
}


let manageDialogVisible = ref(false)
let wifiList = ref([])

function handleMange() {
    manageDialogVisible.value = true
    getWifiList()
}
function getWifiList() {
    RPC2("wifi.wifiList", null).then(res => {
        if (res.data.error) {
            showError(res.data.error)
            return
        }
        wifiList.value = res.data.result

    })
}
function setWifi(func, id) {
    RPC2("wifi.setWifi", [func, id + '']).then(res => {
        if (res.data.error) {
            showError(res.data.error)
            return
        }
        getWifiList()
    })
}
function isValidIP(rule, value, callback) {
    var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
    if (reg.test(value)) {
        callback()
    } else {
        callback(new Error(i18n.global.t('Format error')))
    }
}
const rules = reactive({
    ip: [{ validator: isValidIP, trigger: 'blur' }],
    mask: [{ validator: isValidIP, trigger: 'blur' }],
    gateway: [{ validator: isValidIP, trigger: 'blur' }],
    dns: [{ validator: isValidIP, trigger: 'blur' }],
})

const netFormRef = ref(null)
const net2FormRef = ref(null)
const wifiFormRef = ref(null)

function saveNet() {
    netFormRef.value.validate(valid => {
        if (valid) {
            FUNC("setNetwork", netConfig).then(res => {
                saveCallback(res)
            })
        }
    })
}
function saveNet2() {
    net2FormRef.value.validate(valid => {
        if (valid) {
            FUNC("setNetwork2", netConfig2).then(res => {
                saveCallback(res)
            })
        }
    })
}
function saveWifi() {
    wifiFormRef.value.validate(valid => {
        if (valid) {
            RPC2("wifi.update", [wifiConfig]).then(res => {
                saveCallback(res)
            })
        }
    })
}

function saveCallback(res) {
    if (res.data.error) {
        modal.msgError(i18n.global.t('Save failed'))
    } else {
        modal.msgSuccess(i18n.global.t('Save success'))
    }
}

function showError(error) {
    modal.msgError(`${i18n.global.t('Connect failed')}: code: ${error.code},message:${error.message}`)
}

</script>

<style lang='scss' scoped>
.output {

    .btns {
        text-align: center;
        margin-top: 20px;
    }

    .wifi-item {
        padding: 10px 0 10px 10px;
        border-bottom: 1px solid #ddd;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .el-form-item__content {
        width: 100%;
    }
}
</style>